import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:qunaimedical/components/cell.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/doctor_summary_card.dart';
import 'package:qunaimedical/components/item_option_with_count.dart';
import 'package:qunaimedical/components/item_rounded_option.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/doctor.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/chat/chat_page.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 医生信息界面，如果传递过来医生对象，则直接展示，否则根据医生id去获取。
class DoctorSimpleDetailPage extends StatefulWidget {
  final String doctorId;

  const DoctorSimpleDetailPage({Key key, this.doctorId}) : super(key: key);

  @override
  _DoctorSimpleDetailPageState createState() => _DoctorSimpleDetailPageState();
}

class _DoctorSimpleDetailPageState extends State<DoctorSimpleDetailPage> {
  static String _tag = '_DoctorSimpleDetailPageState';
  Doctor _item;

  @override
  void initState() {
    super.initState();
    _fetchData();
    _fetchDoctorSelectedInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('医生简介')),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                DoctorSummaryCard(
                  margin: EdgeInsets.only(left: 16, top: 16, right: 16),
                  item: _item,
                ),
                Container(
                  color: Colors.white,
                  child: Row(children: [
                    Expanded(
                        child: ItemOptionWithCount(
                            count: _item?.appointedNum ?? 0, text: '咨询人数')),
                    Expanded(
                        child: ItemOptionWithCount(count: 100, text: '好评率')),
                    Expanded(
                        child: ItemOptionWithCount(count: 100, text: '同行认可')),
                  ]),
                ),
                CustomDivider(),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 5, vertical: 16),
                  child: Row(
                    children: [
                      Expanded(
                        child: ItemRoundedOption(
                          bgColor: Color(0xffebfff9),
                          text: '图文咨询',
                          imagePath: 'assets/images/ic_comm_image.png',
                          imageSize: 40,
                          // secondText: '99元/次',
                          // secondTextColor: Colors.red,
                          textColor: Colors.black87,
                        ),
                      ),
                      Expanded(
                        child: ItemRoundedOption(
                          bgColor: Color(0xfffff8e7),
                          text: '电话咨询',
                          textColor: Colors.black87,
                          // secondText: '99元/次',
                          // secondTextColor: Colors.red,
                          imagePath: 'assets/images/ic_comm_phone.png',
                          imageSize: 40,
                        ),
                      ),
                      Expanded(
                        child: ItemRoundedOption(
                          bgColor: Color(0xffecf9ff),
                          text: '私人医生',
                          textColor: Colors.black87,
                          // secondText: '99元/次',
                          // secondTextColor: Colors.red,
                          imagePath: 'assets/images/ic_comm_doctor.png',
                          imageSize: 40,
                        ),
                      )
                    ],
                  ),
                ),
                Divider(),
                Container(
                  height: 50,
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Image.asset(
                        'assets/images/ic_comm.png',
                        width: 20,
                      ),
                      SizedBox(width: 5),
                      Expanded(
                        child: Text(
                          '通过文字、图片、语言和医生进行10次交互咨询',
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Image.asset(
                        'assets/images/ic_arrow_right.png',
                        width: 16,
                        height: 16,
                      ),
                    ],
                  ),
                ),
                CustomDivider(),
                PrimaryLabel('擅长介绍'),
                _buildDescText(_item?.skilled ?? ''),
                PrimaryLabel('预约时间'),
                Container(
                  height: 400,
                  child: GridView(
                    padding: EdgeInsets.all(2),
                    //滑动方向
                    scrollDirection: Axis.horizontal,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      //水平间隔
                      crossAxisSpacing: 2.0,
                      //垂直间隔
                      mainAxisSpacing: 2.0,
                      //一行多少个
                      crossAxisCount: 10,
                      //宽高比 默认1
                      childAspectRatio: 0.5,
                    ),
                    children: _getCells(),
                  ),
                ),
              ],
            ),
          ),
          SafeArea(
            child: Container(
                height: 55,
                child: Row(
                  children: [
                    InkWell(
                      onTap: _favorite,
                      child: Container(
                        width: 100,
                        color: Colors.white,
                        alignment: Alignment.center,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              (_item == null ||
                                      _item.whetherAppointed == '0' ||
                                      _item.whetherAppointed == '')
                                  ? 'assets/images/ic_favorite.png'
                                  : 'assets/images/ic_favorited.png',
                              width: 24,
                              height: 24,
                            ),
                            Text(
                              '收藏',
                              style: TextStyle(fontSize: 11),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: InkWell(
                        onTap: _startIM,
                        child: Container(
                          color: Theme.of(context).primaryColor,
                          child: Text(
                            '咨询',
                            style: TextStyle(color: Colors.white),
                          ),
                          alignment: Alignment.center,
                        ),
                      ),
                    )
                  ],
                )),
          )
        ],
      ),
    );
  }

  List<Widget> _getCells() {
    List<Widget> list = [];
    var times = Constants.timeArray.map((e) => Cell(e)).toList();
    list.add(Cell(''));
    list.addAll(times);
    // 取未来一周
    var now = DateTime.now();
    var weekDays = [];
    for (int i = 0; i < 7; i++) {
      weekDays.add(now.add(Duration(days: i)));
    }
    for (DateTime day in weekDays) {
      list.add(Cell(
          '${day.month.toString().padLeft(2, '0')}-${day.day.toString().padLeft(2, '0')}'));
      for (int i = 0; i < Constants.timeArray.length; i++) {
        String date =
            '${day.year}-${day.month.toString().padLeft(2, '0')}-${day.day.toString().padLeft(2, '0')}';
        Widget cell;
        for (AppointmentInfo info in _infos) {
          if (date == info.freeTime.substring(0, 10) &&
              info.morningAfternoon == Constants.timeArray[i]) {
            cell = Cell('已约', bgColor: Colors.green[100]);
          }
        }
        if (cell == null) {
          cell = Cell('', bgColor: Colors.green[100]);
        }
        list.add(cell);
      }
    }
    return list;
  }

  /// 收藏
  void _favorite() {
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (_item.whetherAppointed == '0' || _item.whetherAppointed == '') {
      _addFavorite();
    } else {
      _removeFavorite();
    }
  }

  void _addFavorite() async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_ADD, {
        'accountId': user.id,
        'recordId': _item.id,
        'recordType': 'doctor',
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _item.whetherAppointed = '1';
            });
          }
        } else {
          ToastUtil.show(response['msg'], context);
        }
      }
    }
  }

  void _removeFavorite() async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_REMOVE, {
        'accountId': user.id,
        'recordId': _item.id,
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _item.whetherAppointed = '0';
            });
          }
        } else {
          ToastUtil.show(response['msg'], context);
        }
      }
    } else {}
  }

  void _startIM() async {
    var user = SPUtils.getUser();
    if (user == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    // 认证: 未认证或者认证失败时，提示用户进行认证。
    if (user.authStatus == 2 || user.authStatus == 4) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行资质认证');
      return;
    }
    // 认证： 待认证时，提示用户等待
    if (user.authStatus == 3) {
      DialogUtils.showAlertDialog(context, '提示', '已提交资料，请等待审核。');
      return;
    }
    if (_item != null &&
        _item.doctorAccount != null &&
        _item.doctorAccount.username != null &&
        _item.doctorAccount.username != '') {
      print('username (im account): ${_item.doctorAccount.username}');
      try {
        // emId: 会话对应环信id, 如果是群组或者聊天室，则为群组id或者聊天室id
        EMConversation conv = await EMClient.getInstance.chatManager
            .getConversation(_item.doctorAccount.username);
        conv.name = _item.fullname;
        Navigator.push(context,
            MaterialPageRoute(builder: (c) => ChatPage(_item.fullname, conv)));
      } on EMError catch (e) {
        print('操作失败，原因是: $e');
      }
    } else {
      Log.d(_tag, '用户信息为空');
    }
  }

  Widget _buildDescText(String content) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Text(
        content,
        style: TextStyle(color: Colors.grey),
      ),
    );
  }

  void _fetchData() async {
    var params = {
      'id': widget.doctorId,
    };
    if (SPUtils.getUser() != null) {
      params['doctorAccountId'] = SPUtils.getUser().id;
    }
    var result = await XHttp.postJson(Urls.FIND_DOCTOR, params);
    if (result != null && result != '') {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (mounted) {
          setState(() {
            _item = Doctor.fromJson(response.data);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  List<AppointmentInfo> _infos = [];

  void _fetchDoctorSelectedInfo() async {
    var data = await XHttp.postJson(
        sprintf(Urls.DOCTOR_SELECTED_INFO, [widget.doctorId]));
    if (data != null && mounted) {
      ListResponse response = ListResponse.fromJson(data);
      setState(() {
        _infos = response.data.map((e) => AppointmentInfo.fromJson(e)).toList();
      });
    }
  }
}

class AppointmentInfo {
  String morningAfternoon;
  String freeTime;

  AppointmentInfo(this.morningAfternoon, this.freeTime);

  factory AppointmentInfo.fromJson(Map<String, dynamic> data) {
    return AppointmentInfo(
      data['morningAfternoon'],
      data['freeTime'],
    );
  }
}
